package com.sanjiahantang.youjiarole.module.me.scheme.presenters;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;

import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiarole.R;
import com.sanjiahantang.youjiarole.base.BaseBean;
import com.sanjiahantang.youjiarole.base.BaseMvpPresenter;
import com.sanjiahantang.youjiarole.base.BaseView;
import com.sanjiahantang.youjiarole.base.CallBack;
import com.sanjiahantang.youjiarole.config.ConfigValue;
import com.sanjiahantang.youjiarole.config.SPConfig;
import com.sanjiahantang.youjiarole.module.cases.models.ICaseModel;
import com.sanjiahantang.youjiarole.module.cases.models.impl.CaseModel;
import com.sanjiahantang.youjiarole.module.cases.views.impl.CaseDetailActivity;
import com.sanjiahantang.youjiarole.module.common.beans.StringBean;
import com.sanjiahantang.youjiarole.module.common.beans.UserOBean;
import com.sanjiahantang.youjiarole.module.common.models.IUserModel;
import com.sanjiahantang.youjiarole.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiarole.module.me.favorite.views.FavoriteCaseView;
import com.sanjiahantang.youjiarole.module.me.scheme.beans.MeCaseOBean;
import com.sanjiahantang.youjiarole.module.me.scheme.beans.MeSchemeCaseListBean;
import com.sanjiahantang.youjiarole.module.me.scheme.beans.MeSchemeListBean;
import com.sanjiahantang.youjiarole.module.me.scheme.beans.SchemeBean;
import com.sanjiahantang.youjiarole.module.me.scheme.beans.SchemeListBean;
import com.sanjiahantang.youjiarole.module.me.scheme.views.MeSchemeView;
import com.sanjiahantang.youjiarole.module.me.scheme.views.impl.MeSchemeCaseDetailActivity;
import com.sanjiahantang.youjiarole.module.programmeprice.views.impl.ProgramOrderActivity;
import com.sanjiahantang.youjiarole.module.programmeprice.views.impl.ProgramPriceActivity;
import com.sanjiahantang.youjiarole.utils.FileUtils;
import com.sanjiahantang.youjiarole.utils.SPUtils;
import com.squareup.picasso.Picasso;

import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.CommonPagerTitleView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sanjiahantang.youjiarole.module.me.scheme.views.MeSchemeView.MESCHEMELIST_ONE;

/**
 * Created by zy on 2017/9/8.
 */

public class MeSchemePresenter extends BaseMvpPresenter<MeSchemeView> {

    private IUserModel userModel;
    private MeSchemeView.OnLoadListener onLoadListener;
    private BaseView.OnLoadListener loadListener;
    private CommonNavigatorAdapter tabAdapter;
    private ICaseModel caseModel;
    private List<SchemeListBean.Data> tabList;
    private QuickAdapter<SchemeBean.Data> schemeAdapter;
    private MeSchemeView.DetailCallBack detailCallBack;
    private String planId;
    private String keyWords;
    private String version;
    private QuickAdapter detailAdapter;
    public MeSchemePresenter() {
        userModel = new UserModel();
        tabList = new ArrayList<>();
        caseModel = new CaseModel();
    }

    public void loadMySchemeList(Context context, final MeSchemeView.OnLoadListener onLoadListener) {
        Map<String, String> params = new HashMap<>();
        userModel.loadSchemeList(context, params, new SchemeListCallBack());
        this.onLoadListener = onLoadListener;

        tabAdapter = new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return tabList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int index) {
                CommonPagerTitleView commonPagerTitleView = new CommonPagerTitleView(context);
                View contentView = LayoutInflater.from(context).inflate(R.layout.item_radio_line, null);
                commonPagerTitleView.setContentView(contentView);
                final RadioButton btn = (RadioButton) contentView.findViewById(R.id.rbItem);
                btn.setText(tabList.get(index).getName());

                commonPagerTitleView.setOnPagerTitleChangeListener(new CommonPagerTitleView.OnPagerTitleChangeListener() {
                    @Override
                    public void onSelected(int i, int i1) {
                        btn.setChecked(true);
                    }

                    @Override
                    public void onDeselected(int i, int i1) {
                        btn.setChecked(false);
                    }

                    @Override
                    public void onLeave(int i, int i1, float v, boolean b) {

                    }

                    @Override
                    public void onEnter(int i, int i1, float v, boolean b) {

                    }
                });
                btn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onLoadListener.switchPages(index);
                        reloadData(context, tabList.get(index).getId());
                    }


                });
                commonPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        onLoadListener.switchPages(index);
                        reloadData(context, tabList.get(index).getId());
                    }
                });
                return commonPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                return null;
            }
        };
        onLoadListener.initTabs(tabAdapter);


        schemeAdapter = new QuickAdapter<SchemeBean.Data>(context, R.layout.item_case_list) {
            @Override
            protected void convert(BaseAdapterHelper helper, SchemeBean.Data item) {
                helper.setText(R.id.tv_case_detail, item.getRoomType() + " ， " + item.getStyle());
                Picasso.with(context).load(FileUtils.rePath(item.getImage())).into((ImageView) helper.getView(R.id.ivCaseMain));
                helper.setVisible(R.id.llCollect, false);
                helper.setVisible(R.id.txtCaseTitle, false);
                helper.setOnClickListener(R.id.ivCaseMain, new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        goPageSimply(context, CaseDetailActivity.class);
                    }
                });
            }
        };

        onLoadListener.initList(schemeAdapter);
    }

    private void reloadData(Context context, String id) {
        Map<String, String> params = new HashMap<>();
        mView.showProgress();
        userModel.loadSchemeDetail(context, params, new SchemeDetailCallBack());
    }

    public void loadMySchemeListFirst(Context context) {
        Map<String, Object> map = new HashMap<>();
        map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        map.put(KEY_PAGE, 1);
        map.put(KEY_PAGE_SIZE, DEFAULT_PAGE_SIZE);
        Map<String, Object> params = new HashMap<>();
        params.put("designPhone",SPUtils.get(context, KEY_PHONE, ""));
        params.put("pushState3D",1);
        map.put(KEY_PARAM, params);
        mView.showProgress();
        userModel.loadSchemeListFirst(context, map, new LoadSchemeListFirstCallBack());

    }

    public void setOncliclisener(BaseView.OnLoadListener oncliclisener) {
        this.loadListener = oncliclisener;

    }
    //我的方案中first方案列表
    public void loadMySchemeCaseList(Context context,String id) {
        Map<String, String> map = new HashMap<>();
        map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        map.put("requireId", id);
        mView.showProgress();
        userModel.loadSchemeCaseList(context,map,new LoadSchemeCaseListCallBack());
    }
    //我的方案中second方案列表
    public void loadCaseById(Context context, int id_o) {
        Map<String, String> map = new HashMap<>();
        map.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        map.put(KEY_ID, ""+id_o);
        mView.showProgress();
        userModel.loadSchemeCaseDetailList(context,map,new CallBack<MeCaseOBean> (){

            @Override
            public void onSuccess(MeCaseOBean response, Context context, Object tag) {
                if (mView==null){
                    return;
                }
                mView.hideProgress();
                if (response != null && response.getCode()==RESPONSE_CODE_SUC){
                    if (detailAdapter == null) {
                        detailAdapter = new QuickAdapter<MeCaseOBean.PicList>(context, R.layout.item_case_info) {
                            @Override
                            protected void convert(BaseAdapterHelper helper, MeCaseOBean.PicList item) {
                                ImageView ivIcon = helper.getView(R.id.ivIcon);
                                helper.setText(R.id.txtName, item.getPicCaName());
                                ivIcon.setImageResource(MeSchemeView.IMAGE_RES_IDS[item.getPicCaId()]);
                                ImageView ivPhoto = helper.getView(R.id.ivPhoto);
                                Picasso.with(context).load(FileUtils.rePath(item.getUrl()))
                                        .placeholder(R.drawable.i_match)
                                        .into(ivPhoto);
                                // SPUtils.put(context, "planId", "" + item.getPlanId());
                            }
                        };
                        detailCallBack.initAdapter(detailAdapter);
                    }
                }
                List<MeCaseOBean.PicList> picList = new ArrayList<>();
                if (response.getData() != null && response.getData().getPicList() != null){
                    for (int i = 0; i < response.getData().getPicList().size(); i++) {
                        if (15 != response.getData().getPicList().get(i).getPicCaId()) {
                            picList.add(response.getData().getPicList().get(i));
                        } else {
                            ConfigValue.data = response.getData().getPicList().get(i);
                        }
                    }
                }
                detailAdapter.clear();
                detailAdapter.addAll(picList);
                detailCallBack.loadData(response.getData());
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
            }
        });

    }

    public void addCollectInfo(final Context context, int id) {

        Map<String,Object> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put(FavoriteCaseView.KEY_ROLE_TYPE,1);
        param.put(KEY_PHONE,SPUtils.get(context, SPConfig.PHONE,"").toString());
        param.put(KEY_TYPE,1);
        param.put(FavoriteCaseView.KEY_FAVORITE_ID,id);
        mView.showProgress();
        caseModel.addCollectInfo(context,param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                mView.hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC){
                    Utils.showToast(context,"收藏成功");
                }else{
                    Utils.showToast(context,"很抱歉，收藏案例失败");
                }

            }
            @Override
            public void onFailure(String message) {
                Utils.showToast(context,"很抱歉，收藏案例失败");
               mView.hideProgress();
            }
        });
    }
    public void setDetailCallBack(MeSchemeView.DetailCallBack detailCallBack) {
        this.detailCallBack = detailCallBack;
    }
     //检查是否已经下单
    public void checkcCustomerIsOrder(Context context, String s,String verion) {
        this.version=verion;
        planId=s;
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put("planId",s);
        caseModel.checkOrderIsCommit(context,param,new CheckOrderIsCommitCallBack());
    }

    //检查是否已经下单
    public void checkcCustomerIsOrder(Context context, String s, String verion, final BaseView.OnLoadListener listener) {
        this.version=verion;
        planId=s;
        Map<String,String> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put("planId",s);
        caseModel.checkOrderIsCommit(context, param, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (response != null && response.getCode() == RESPONSE_CODE_SUC){
                    listener.onLoad(response.getData());
                }
            }

            @Override
            public void onFailure(String message) {
                listener.onLoad("false");
            }
        });
    }
    //推荐项目经理
    public void UpdateProjectDesign(Context context ,String type,UserOBean.Data item,int ucrId,final int id) {
        Map<String,String> map=new HashMap<>();
        map.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        map.put(KEY_PHONE,item.getPhone());
        map.put("name",item.getUserName());
        map.put("state",type);
        map.put("ucrId",String.valueOf(ucrId));
        userModel.UpdataProjectInfo(context,map, new CallBack<StringBean>() {
            @Override
            public void onSuccess(StringBean response, Context context, Object tag) {
                if (response.getCode()==RESPONSE_CODE_SUC){
                    loadCaseById(context,id);
                    Utils.showToast(context,"推荐成功");
                }else {
                    Utils.showToast(context,"推荐失败");
                }


            }

            @Override
            public void onFailure(String message) {

            }
        });

    }

    public void addRequireSubcontractInfoByProject(final Context context, UserOBean.Data data, int ucrId, final BaseView.OnLoadListener listener) {
        Map<String,Object> param = new HashMap<>();
        param.put(KEY_TOKEN,ConfigValue.DATA_KEY);
        param.put("ucriId",ucrId);
        param.put("projectPhone",data.getPhone());
        param.put("projectName",data.getUserName());
        if (mView == null) return;
        mView.showProgress();
        userModel.addRequireSubcontractInfoByProject(context,param, new CallBack<BaseBean>() {
            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                if (mView == null) return;
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC){
                    listener.onLoad(response);
                }else{
                    Utils.showToast(context,"分包失败");
                }
            }

            @Override
            public void onFailure(String message) {
                if (mView == null) return;
                mView.hideProgress();
                Utils.showToast(context,"分包失败");
            }
        });
    }

    private class CheckOrderIsCommitCallBack implements CallBack<StringBean> {

        @Override
        public void onSuccess(StringBean response, Context context, Object tag) {
            if (mView == null) return;
            mView.hideProgress();
            Intent intent;
            if (response != null && response.getCode() == RESPONSE_CODE_SUC && response.getData() != null && response.getData().equals("false")){
                intent=new Intent(context,ProgramPriceActivity.class);
                intent.putExtra("requireId",planId);
                intent.putExtra(KEY_VERSION,version);
              //  intent.putExtra(KEY_TYPE,0);//清单
                context.startActivity(intent);
            }else{
                ConfigValue.param = null;
                intent=new Intent(context,ProgramOrderActivity.class);
                intent.putExtra(KEY_ID,Integer.valueOf(planId));
                context.startActivity(intent);
            }

        }

        @Override
        public void onFailure(String message) {
            if (mView == null) return;
            mView.hideProgress();
        }
    }
    private class LoadSchemeCaseListCallBack implements CallBack<MeSchemeCaseListBean> {

        @Override
        public void onSuccess(MeSchemeCaseListBean response, Context context, Object tag) {
            if (mView == null) return;
            mView.hideProgress();
            if (response.getData()!=null){
                Object[] object = new Object[2];
                object[0] = MESCHEMELIST_ONE;
                object[1] = response.getData().getInformationList();
                loadListener.onLoad(object);
            }
        }

        @Override
        public void onFailure(String message) {
            if (mView == null) return;
            mView.hideProgress();
        }
    }
    private class LoadSchemeListFirstCallBack implements CallBack<MeSchemeListBean> {

        @Override
        public void onSuccess(MeSchemeListBean response, Context context, Object tag) {
            if (mView == null) return;
            mView.hideProgress();
            if (response.getData()!=null){
                Object[] object = new Object[2];
                object[0] = MESCHEMELIST_ONE;
                object[1] = response.getData().getList();
                loadListener.onLoad(object);
            }

        }

        @Override
        public void onFailure(String message) {
            if (mView == null) return;mView.hideProgress();
        }
    }

    private class SchemeListCallBack implements CallBack<SchemeListBean> {

        @Override
        public void onSuccess(SchemeListBean response, Context context, Object tag) {
            mView.hideProgress();
            tabList.clear();

            tabList.addAll(response.getData());
            tabAdapter.notifyDataSetChanged();

            if (tabList.size() > 0) {
                reloadData(context, tabList.get(0).getId());
            }
        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }

    private class SchemeDetailCallBack implements CallBack<SchemeBean> {

        @Override
        public void onSuccess(SchemeBean response, Context context, Object tag) {
            mView.hideProgress();
            schemeAdapter.clear();
            schemeAdapter.addAll(response.getData());
        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }
}
